// common.c -- Defines some global functions.
//             From JamesM's kernel development tutorials.

#include "common.h"
#include "scrn.h"
/*TODO: no assert add*/
u8int* memcpy(u8int* dest,const u8int* src,s32int count)
{
    u8int* tmp = dest;

    while(count-->0)
        *dest++ = *src++;
    return tmp; 
}
u8int* memset(u8int* dest,u8int val, s32int count)
{
   u8int* tmp = dest;
   while(count-- > 0)
       *dest++ = val;
   return tmp;
}
u16int *memsetw(u16int* dest,u16int val,s32int count) 
{
   u16int* tmp = dest;

   while(count-- > 0)
       *dest ++ = val;
   return tmp;
}
u16int* memcpyw(u16int* dest, u16int* src, s32int count)
{
   u16int* tmp = dest;

   while(count-- >0)
       *dest++ = *src++;

   return tmp;
}
u32int strlen(u8int* str)
{
   u32int len = 0;
   while(*str++ != 0)
       len ++;

   return len;
}
u8int inportb(u16int _port)
{
   u8int rv;
   __asm__ __volatile__("inb %1,%0":"=a"(rv):"dN"(_port));

   return rv;
}
void outportb(u16int _port,u8int _data)
{
    __asm__ __volatile__("outb %1, %0"::"dN"(_port),"a"(_data));
}

int strcmp(char *str1, char *str2)
{
      int i = 0;
      int failed = 0;
      while(str1[i] != '\0' && str2[i] != '\0')
      {
          if(str1[i] != str2[i])
          {
              failed = 1;
              break;
          }
          i++;
      }
      // why did the loop exit?
      if( (str1[i] == '\0' && str2[i] != '\0') || (str1[i] != '\0' && str2[i] == '\0') )
          failed = 1;
  
      return failed;
}


extern void panic(const char *message, const char *file, u32int line)
{
    // We encountered a massive problem and have to stop.
    asm volatile("cli"); // Disable interrupts.

    puts("PANIC(");
    puts(message);
    puts(") at ");
    puts(file);
    puts(":");
    puts_dec(line);
    puts("\n");
    // Halt by going into an infinite loop.
    for(;;);
}

extern void panic_assert(const char *file, u32int line, const char *desc)
{
    // An assertion failed, and we have to panic.
    asm volatile("cli"); // Disable interrupts.

    puts("ASSERTION-FAILED(");
    puts(desc);
    puts(") at ");
    puts(file);
    puts(":");
    puts_dec(line);
    puts("\n");
    // Halt by going into an infinite loop.
    for(;;);
}
